package com.hsq.reflection.testReflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectTest {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException, ClassNotFoundException {
        Class<PrivateTest> privateTestClass = PrivateTest.class;
        PrivateTest privateTest = privateTestClass.newInstance();
        Field name = privateTestClass.getDeclaredField("name");
        name.setAccessible(true);
        name.set(privateTest, "Java");
        Method method = privateTestClass.getMethod("getName");
        Object invoke = method.invoke(privateTest);
        System.out.println("name=" + invoke);

        Class<?> fileCls = Class.forName("java.io.File");
        Constructor<?>[] declaredConstructors = fileCls.getDeclaredConstructors();
        for (Constructor constructor: declaredConstructors) {
            System.out.println(constructor);
        }

        String filePath = "D:\\git_turtle\\mynew.txt";
        Constructor<?> declaredConstructor = fileCls.getDeclaredConstructor(String.class);
        Object fileObj = declaredConstructor.newInstance(filePath);

        Method method1 = fileCls.getMethod("createNewFile");
        method1.invoke(fileObj);
        System.out.println(fileObj.getClass());
        System.out.println("创建成功：" + filePath);
    }
}

class PrivateTest {
    private String name = "CPP";

    public String getName() {
        return this.name;
    }
}
